package org.example;

import org.apache.commons.lang3.StringUtils;
import org.example.config.ConfigLoader;

import java.sql.*;

public class DBUtil {
    private final String className;
    private final String url;
    private final String username;
    private final String password;
    private Connection conn;

    public DBUtil() {
        ConfigLoader CONFIG_LOADER = new ConfigLoader();
        className = CONFIG_LOADER.getConfigValue("datasource.driver-class-name");
        url = CONFIG_LOADER.getConfigValue("datasource.url");
        username = CONFIG_LOADER.getConfigValue("datasource.username");
        password = CONFIG_LOADER.getConfigValue("datasource.password");

        try {
            Class.forName(className);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            System.out.println("初始化DBUtil异常:" + e.getMessage());
            System.exit(0);
        }
    }


    public int update(final String sql) throws Exception {
        if (StringUtils.isBlank(sql)) return 0;
        try (Statement stmt = conn.createStatement()) {
            int update = stmt.executeUpdate(sql);
            return update;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }

    public String select(final String sql) throws Exception {
        if (StringUtils.isBlank(sql)) return null;
        String result = null;
        try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
            if (rs.next()) {
                result = rs.getString(1);
            }
            return result;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }

    public void close() {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
